import asyncio
from contextlib import AsyncExitStack
from typing import Optional

from mcp import StdioServerParameters, ClientSession
from mcp.client.stdio import stdio_client


class MCPClient:

    server_path= "server.py"

    def __init__(self):
        #创建线程管理栈
        self.exit_stack = AsyncExitStack()
        self.session: Optional[ClientSession] = None

    """创建连接服务端"""
    async def connect_to_server(self, server_path: str):
        # 一、创建StdioServerParameter参数信息
        server_parameters = StdioServerParameters(
            command="python",
            args=[server_path],
            env=None
        )
        # 二、 创建stdioClient
        client = stdio_client(server=server_parameters)
        stdio_transport = await self.exit_stack.enter_async_context(client)
        read_stream, write_stream = stdio_transport

        # 三、创建ClientSession
        client_session = ClientSession(read_stream, write_stream)
        self.session = await self.exit_stack.enter_async_context(client_session)
        # 四、初始化session
        await self.session.initialize()
        #五、列出所有可用的工具
        response = await self.session.list_tools()
        tools = response.tools
        print("\nConnected to server with tools:",tools)

    #关闭连接
    async def cleanup(self):
        await self.exit_stack.aclose()

async def main():
    client = MCPClient()
    try:
        await client.connect_to_server(client.server_path)
    except Exception as e:
        print(f"Error: {str(e)}")
    finally:
        await client.cleanup()

if __name__ == "__main__":
    asyncio.run(main())